﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using Netduino4Fun.DesktopAssistant.Windows.Properties;


namespace Netduino4Fun.DesktopAssistant.Windows.Netduino
{
    public class SerialConnection : Connection
    {
        private SerialPort serialPort;

        public SerialConnection()
        {
            Settings settings = Properties.Settings.Default;
            this.serialPort = new SerialPort(settings.Netduino_SerialPort_PortName,
                                                settings.Netduino_SerialPort_BaudRate, settings.Netduino_SerialPort_Parity,
                                                settings.Netduino_SerialPort_DataBits, settings.Netduino_SerialPort_StopBits);
            this.serialPort.Handshake = settings.Netduino_SerialPort_Handshake;
            this.serialPort.ReadTimeout = settings.Netduino_SerialPort_ReadTimeout;
            this.serialPort.WriteTimeout = settings.Netduino_SerialPort_WriteTimeout;
            this.serialPort.Encoding = Encoding.UTF8;
        }

        public override void Open()
        {
            this.serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
            this.serialPort.Open();
        }

        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string line = this.serialPort.ReadLine();
            while (line != null)
            {
                OnLineReceived(line);
                line = this.serialPort.ReadLine();
            }
        }

        protected override void Write(string line)
        {
            this.serialPort.WriteLine(line);
        }
    }
}
